﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using FantastPlatform.Community.IService;
using FantastPlatform.Framework;
using FantastPlatform.Framework.Core;
using FantastPlatform.Community.IMode;
using System.Net;
using System.Configuration;

namespace FantastPlatform.Community.UI.Service
{
    public partial class PersonSearchService : BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            LoginEmployee = Session["User"] as FantastPlatform.Framework.Model.Employee;
            IPersonService personService = ServiceFactory.CreateService<IPersonService>();
            IPerson person;
            IList<IPerson> personList;
            IList<Sort> sorts = new List<Sort>();
            ConditionGroup group = new ConditionGroup();
            int totalCount = 0;
            Condition enableCondition = new Condition() { Type = typeof(bool).FullName, Field = "Enable", Value1 = true };
            group.Conditions.Add(enableCondition);
            switch (Action)
            {
                case "Search":
                    personList = personService.Search(group, sorts, PageSize, SelfPage, out totalCount);
                    var objperson = from n in personList
                                    select new
                                    {
                                        Id = n.Id,
                                        Name = n.Name,
                                        Sex = n.Sex,
                                        QQ = n.QQ,
                                        Phone = n.Phone,
                                        IdCard = n.IdCard,
                                        BaseInfo = GetHouseAddressByPersonId(n.Id),
                                        CreateDateStr = n.CreateDate.ToString(),
                                        ModifyDate = n.ModifyDate.ToString()
                                    };
                    ReturnList(totalCount, objperson.ToList());

                    break;
                case "SearchHistory":
                    group.Conditions.Clear();
                    group.Conditions.Add(new Condition() { Type = typeof(bool).FullName, Field = "Enable", Value1 = false });
                    personList = personService.Search(group, sorts, PageSize, SelfPage, out totalCount);
                    objperson = from n in personList
                                select new
                                {
                                    Id = n.Id,
                                    Name = n.Name,
                                    Sex = n.Sex,
                                    QQ = n.QQ,
                                    Phone = n.Phone,
                                    IdCard = n.IdCard,
                                    BaseInfo = GetHouseAddressByPersonId(n.Id),
                                    CreateDateStr = n.CreateDate.ToString(),
                                    ModifyDate = n.ModifyDate.ToString()
                                };
                    ReturnList(totalCount, objperson.ToList());

                    break;

                case "SearchByCondition":
                    string Searchjson = RepairString(Data);
                    person = JsonToEntity<FantastPlatform.Community.Model.Person>(Searchjson);
                    if (!string.IsNullOrEmpty(person.Name))
                    {
                        Condition condition1 = new Condition() { Type = typeof(string).FullName, Field = "Name", Value1 = '%' + person.Name + '%', Comparison = Comparisons.Like, Relation = Relations.And };
                        group.Conditions.Add(condition1);
                    }
                    if (!string.IsNullOrEmpty(person.Phone))
                    {
                        Condition condition2 = new Condition() { Type = typeof(string).FullName, Field = "Phone", Value1 = '%' + person.Phone + '%', Comparison = Comparisons.Like, Relation = Relations.And };
                        group.Conditions.Add(condition2);
                    }
                    if (!string.IsNullOrEmpty(person.IdCard))
                    {
                        Condition condition3 = new Condition() { Type = typeof(string).FullName, Field = "IdCard", Value1 = '%' + person.IdCard + '%', Comparison = Comparisons.Like, Relation = Relations.And };
                        group.Conditions.Add(condition3);
                    }
                    personList = personService.Search(group, sorts, PageSize, SelfPage, out totalCount);

                    var obj = from n in personList
                              select new
                              {
                                  Id = n.Id,
                                  Name = n.Name,
                                  Sex = n.Sex,
                                  QQ = n.QQ,
                                  Phone = n.Phone,
                                  IdCard = n.IdCard,
                                  BaseInfo = GetHouseAddressByPersonId(n.Id),
                                  CreateDateStr = n.CreateDate.ToString(),
                                  ModifyDate = n.ModifyDate.ToString()
                              };
                    var objList = obj.ToList();
                    ReturnList(objList.Count, objList);
                    break;

                case "Get":
                    person = personService.Get(Id);
                    var objpersonInfo = (new
                              {
                                  Id = person.Id,
                                  Name = person.Name,
                                  Sex = person.Sex,
                                  QQ = person.QQ,
                                  Phone = person.Phone,
                                  IdCard = person.IdCard,
                                  BaseInfo = GetHouseAddressByPersonId(person.Id)

                              });
                    ReturnObj(objpersonInfo);
                    break;
                case "GetDetails":
                    person = personService.Get(Id);
                    string DetailsInfo = string.Empty;
                    DetailsInfo = GetPersonInfo(person.IdCard);
                    string jsonStr = "{ 'success': 'true', 'data': " + DetailsInfo + "}";
                    Response.Write(jsonStr);
                    Response.End();
                    break;
            }
        }

        private string GetHouseAddressByPersonId(int personId)
        {
            try
            {
                int totalCount = 0;
                string address = "";
                if (personId == 0)
                {
                    return address;
                }
                IBusinessPersonService bpService = ServiceFactory.CreateService<IBusinessPersonService>();
                IHouseHoldPersonService hhService = ServiceFactory.CreateService<IHouseHoldPersonService>();
                ConditionGroup group = new ConditionGroup();
                group.Conditions.Add(new Condition { Field = "Enable", Type = typeof(bool).FullName, Value1 = true });

                group.Conditions.Add(new Condition { Field = "Person.Id", Type = typeof(Int32).FullName, Value1 = personId, Relation = Relations.And });
                IList<IBusinessPerson> bPersonList = bpService.Search(group, null, Int32.MaxValue, 1, out totalCount);
                if (totalCount > 0)
                {
                    address = bPersonList[0].Business.Street.Name + bPersonList[0].Business.Address;
                    //bPersonList[0].Business.Station.Name + bPersonList[0].Business.ResponsibilityArea.Name + 

                }
                IList<IHouseHoldPerson> hhList = hhService.Search(group, null, Int32.MaxValue, 1, out totalCount);
                if (totalCount > 0)
                {
                    address = hhList[0].HouseHold.HouseDistrict.Street.Name + hhList[0].HouseHold.HouseDistrict.Address + hhList[0].HouseHold.Number;
                    //hhList[0].HouseHold.HouseDistrict.Station.Name + hhList[0].HouseHold.HouseDistrict.ResponsibilityArea.Name + 

                }
                return address;
            }
            catch (Exception)
            {
                return "";
            }

        }

        private string GetPersonInfo(string IdCard)
        {
            string baseInfo = string.Empty;
            string changeIdCard = string.Empty;
            if (IdCard.Length == 18)
            {
                changeIdCard = GetChangeIdCard(IdCard);
            }
            else if (IdCard.Length == 15)
            {
                changeIdCard = GetChangeIdCard1(IdCard);
            }
            else
            {
                changeIdCard = null;
            }
            baseInfo = BaseInfo(changeIdCard);

            return baseInfo;
        }

        /// <summary>
        /// 基础字符串定义
        /// </summary>
        static string InfoStr = "&F_SFZH=";
        static string qkljStr = "&tabId=qklj&params=";
        /// <summary>
        /// 18位身份证字符处理
        /// </summary>
        /// <param name="idcard"></param>
        /// <returns></returns>
        static string GetChangeIdCard(string idcard)
        {
            string changeIdcard = "";
            WebClient wc = new WebClient();
            byte[] PersonResponse = wc.DownloadData(ConfigurationManager.AppSettings["resultInfo"] + InfoStr + idcard);

            string sss = System.Text.Encoding.GetEncoding("utf-8").GetString(PersonResponse);

            string mark = "eyJTRlpII";

            if (sss.Contains(mark))
            {
                int index = sss.IndexOf(mark);
                changeIdcard = sss.Substring(index, 40);
            }

            return changeIdcard;
        }

        /// <summary>
        /// 15位身份证字符处理
        /// </summary>
        /// <param name="idcard"></param>
        /// <returns></returns>
        static string GetChangeIdCard1(string idcard)
        {
            string changeIdcard = "";
            WebClient wc = new WebClient();
            byte[] PersonResponse = wc.DownloadData(ConfigurationManager.AppSettings["resultInfo"] + InfoStr + idcard);

            string sss = System.Text.Encoding.GetEncoding("utf-8").GetString(PersonResponse);

            string mark = "eyJT";

            if (sss.Contains(mark))
            {
                int index = sss.IndexOf(mark);
                changeIdcard = sss.Substring(index, 36);
            }

            return changeIdcard;
        }

        /// <summary>
        /// 根据加密身份证字符，得到详细基本信息
        /// </summary>
        /// <param name="IdCardInfo"></param>
        /// <returns></returns>
        static string BaseInfo(string IdCardInfo)
        {
            string BaseInfo = "";
            WebClient wbc = new WebClient();
            byte[] baseInfo = wbc.DownloadData(ConfigurationManager.AppSettings["baseInfo"] + "&params=" + IdCardInfo);
            string baseInfoStr = System.Text.Encoding.GetEncoding("utf-8").GetString(baseInfo);

            BaseInfo = GetBaseIndo(baseInfoStr);
            return BaseInfo;
        }

        /// <summary>
        /// 处理返回的字符串，返回基本信息
        /// </summary>
        /// <param name="baseInfo"></param>
        /// <returns></returns>
        static string GetBaseIndo(string baseInfo)
        {
            string BaseInfoo = string.Empty;
            try
            {
                #region 处理返回的字符串
                string markH = "{";
                string markE = "}";
                if (baseInfo.Length > 0)
                {
                    if (baseInfo.Contains(markH) || baseInfo.Contains(markE))
                    {
                        int Hcount = baseInfo.IndexOf(markH);
                        int Ecount = baseInfo.LastIndexOf(markE);
                        BaseInfoo = baseInfo.Substring(Hcount, Ecount);
                        BaseInfoo = BaseInfoo.Replace("]);", "");
                        BaseInfoo = BaseInfoo.Replace("</script>", "");
                        BaseInfoo = BaseInfoo.Trim();
                    }
                }
                #endregion
            }
            catch (Exception ex)
            {
            }
            return BaseInfoo;
        }

    }

}